﻿(function (window, undefined) {

    //删除数据
    window.app.deleteItem = function (dataTable, url) {
        var $dataTable = $("#" + dataTable);
        if ($dataTable.length === 0) {
            window.app.message("实现错误，列表Id给错。");
            return;
        }
        var ids = new Array();


        if ($dataTable.DataTable().rows()) {
            var list = $dataTable.DataTable().rows({ selected: true }).data();
            $.each(list, function (index, item) {
                ids.push(item.id);
            });
        }
        else {
            $dataTable.find("tbody tr").each(function (x) {
                var checkbox;
                if ($(this).find(".checkColumn").length > 0) {
                    checkbox = $(this).find(".checkColumn input");
                } else {
                    checkbox = $(this).find("td:eq(0) input");
                }

                if (checkbox.length > 0 && checkbox.prop('checked')) {
                    ids.push(checkbox.val());
                }
            });
        }


        if (ids.length === 0) {
            window.app.message("请选中一项。");
            return;
        }

        swal({
            title: "请确认是否删除？",
            text: "您正在进行删除操作，该操作不可逆!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger"
        }).then(function (isConfirm) {
            if (isConfirm === true) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: { "ids": ids },
                    dataType: "json",
                    success: function (data) {
                        if (data.errors.length > 0) {
                            swal("出错啦！", data.errors, "error");
                        } else {

                            swal({
                                title: "提示",
                                text: "你已经删除成功",
                                type: "success",
                                timer: 2000
                            });

                            if (data.redirectToUrl == null || data.redirectToUrl.length === 0) {
                                $('#' + dataTable).DataTable().ajax.reload();
                                $('#' + dataTable).find("thead th input").attr("checked", false);
                            } else if (data.redirectToUrl.indexOf("javascript:") >= 0) {
                                eval(data.redirectToUrl.substr(10, data.redirectToUrl.length - 10));
                            } else if (data.redirectToUrl != null && data.redirectToUrl.length > 0) {

                                window.app.modalClose();
                                window.app.loadUI(data.redirectToUrl); //加载其他页面
                            }
                        }
                    }
                });
            }
        });
    };
    //刷新DataTable、搜索
    window.app.search = function (button) {
        //兼容老界面
        if (typeof button == "undefined") {
            if ($(".DTFC_Cloned").length > 0) {
                throw "发现定义了冻结列，需要给按钮的data-search属性赋值dataTable的Id";
            }

            var $dataTable = $(".dataTable");
            $dataTable.each(function (index, item) {
                var $item = $(item);

                if (true === $item.is(":visible")) {
                    $item.DataTable().ajax.reload();
                }
            });
        }
        else {
            var search = $(button).data("search");
            $(search).DataTable().ajax.reload();
        }
    };
    window.app.searchRseset = function (button) {

        var $form = $(button).parents("form");
        $form[0].reset();
        //$form.form("clear");

        //清除下拉框
        $form.find("li.active input").removeAttr("checked");
        $form.find("li.active").removeClass("active");
        $form.find(".dropdown-label").empty();

        //清空日历控件的隐藏域
        $form.find(".hiddenDate").val("");
        //清空自定义控件自带的隐藏域
        $form.find(".form-group input[type='hidden']").val("");

        window.app.search($(button).prev()[0]);

        return true;
    };

    window.app.checkAllItem = function (dataTable, checkbox) {

        var $dataTable = $("#" + dataTable).DataTable();
        if (checkbox.checked) {

            $dataTable.rows().select();
        } else {

            $dataTable.rows().deselect();
        }
    }

    var loadingHandle;
    //加载界面
    window.app.loadUI = function (url) {
        if (loadingHandle != null)
            loadingHandle.abort();
        loadingHandle = window.app.ajax({
            headers: {
                pjax: true
            },
            url: url,
            type: "post",
            beforeSend: function () {
                //Pace.restart();
            },
            error: function (response, status, xhr) {
                var html = jQuery.parseHTML(response, true);

                $("#divMainContent").empty();
                $("#divMainContent").html(html);

                loadingHandle = null;
            },
            success: function (response, status, xhr) {
                if (response === "" && xhr.getResponseHeader("X-Responded-JSON") != null) {
                    var responded = jQuery.parseJSON(xhr.getResponseHeader("X-Responded-JSON"));

                    if (responded.status === 401)
                        window.location.href = responded.headers.location;
                    else {
                        alert(xhr.getResponseHeader("X-Responded-JSON"));
                    }

                    return false;
                }
                if (response.errors) {
                    app.error(response.errors);
                    return false;
                }
                var html = jQuery.parseHTML(response, true);


                $("#divMainContent").html(html);

                window.history.pushState(null, null, url);

                if ($.validator && $('#modalcontent form').length > 0) {
                    $.validator.unobtrusive.parse($('#modalcontent form'));
                    $('#modalcontent form').validateBootstrap();
                }

                loadingHandle = null;
            }
        });
    };

    window.addEventListener('popstate', function (e) {

        if (location.pathname === "/") {

        } else {
            window.app.loadUI(location.pathname);
        }
    });
}(window));